//package com.breakfast.fun.ui.user.address;
//
//import android.Manifest;
//import android.content.Intent;
//import android.content.pm.PackageManager;
//import android.net.Uri;
//import android.os.Build;
//import android.support.annotation.NonNull;
//import android.support.annotation.RequiresApi;
//import android.support.v4.app.ActivityCompat;
//import android.support.v4.content.ContextCompat;
//import android.view.View;
//import android.widget.Button;
//import android.widget.EditText;
//import android.widget.LinearLayout;
//import android.widget.ListView;
//import android.widget.TextView;
//
//import com.baidu.location.BDLocation;
//import com.baidu.location.BDLocationListener;
//import com.baidu.location.LocationClient;
//import com.baidu.location.LocationClientOption;
//import com.baidu.location.Poi;
//import com.baidu.mapapi.map.BaiduMap;
//import com.baidu.mapapi.map.InfoWindow;
//import com.baidu.mapapi.map.MapStatus;
//import com.baidu.mapapi.map.MapStatusUpdateFactory;
//import com.baidu.mapapi.map.MapView;
//import com.baidu.mapapi.map.MyLocationData;
//import com.baidu.mapapi.model.LatLng;
//import com.breakfast.fun.Constant;
//import com.breakfast.fun.R;
//import com.breakfast.fun.adapter.user.ChooseBuildingAdapter;
//import com.breakfast.fun.adapter.user.ChooseRoadAdapter;
//import com.breakfast.fun.base.BaseActivity;
//import com.breakfast.fun.data.entity.user.address.Building;
//import com.breakfast.fun.data.entity.user.address.BuildingData;
//import com.breakfast.fun.data.entity.user.address.Road;
//import com.breakfast.fun.data.entity.user.address.RoadData;
//import com.breakfast.fun.event.FinishEvent;
//import com.breakfast.fun.util.L;
//import com.breakfast.fun.util.ScreenUtil;
//import com.breakfast.fun.util.T;
//import com.breakfast.fun.view.widget.CustomDialog;
//import com.breakfast.fun.view.widget.TitleBarView;
//
//import org.greenrobot.eventbus.EventBus;
//import org.greenrobot.eventbus.Subscribe;
//import org.greenrobot.eventbus.ThreadMode;
//
//import java.util.ArrayList;
//import java.util.List;
//
//import butterknife.Bind;
//
//public class ChooseBuildingActivity extends BaseActivity<ChooseBuildingPresenter, ChooseBuildingModel> implements ChooseBuildingContract.View {
//
//    @Bind(R.id.tbv_choose_building)
//    TitleBarView mTbvChooseBuilding;
//    @Bind(R.id.et_choose_building_search)
//    EditText mEtChooseBuildingSearch;
//    @Bind(R.id.tv_choose_building_search)
//    TextView mTvChooseBuildingSearch;
//    @Bind(R.id.lv_choose_building)
//    ListView mLvChooseBuilding;
//    @Bind(R.id.mv_choose_building)
//    MapView mMvChooseBuilding;
//    @Bind(R.id.ll_choose_building_mapview_parent)
//    LinearLayout mLlChooseBuildingMapViewParent;
//
//    private ChooseRoadAdapter mRoadAdapter;
//    private ChooseBuildingAdapter mBuildingAdapter = null;
//
//    private BaiduMap mBaiduMap = null;
//    // 定位相关
//    LocationClient mLocClient;
//    public MyLocationListenner myListener = new MyLocationListenner();
//
//    boolean isFirstLoc = true; // 是否首次定位
//    private List<String> perssionList = new ArrayList<String>();
//    private final int LOCATION_RESULT = 1;
//
//    private static int depth = 0;
//    private CustomDialog dialog = null;
//    private InfoWindow infoWindow = null;
//
//    @Override
//    public int getLayoutId() {
//        return R.layout.activity_choose_building;
//    }
//
//    @Override
//    public void initView() {
//        EventBus.getDefault().register(this);
//
//        mTbvChooseBuilding.setTitleNoRight("选择大楼");
//        mTbvChooseBuilding.setBack(this);
//        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mLlChooseBuildingMapViewParent.getLayoutParams();
//        params.height = (ScreenUtil.getScreenHeight(context) - ScreenUtil.getStatusHeight(context) - 48 * 2) / 2;
//        //
//        if (Build.VERSION.SDK_INT >= 23) {
//            if (ContextCompat.checkSelfPermission(this,
//                    Manifest.permission.ACCESS_FINE_LOCATION)
//                    != PackageManager.PERMISSION_GRANTED) {
//
//                /**
//                 * 由于手机定制系统这个方法默认返回false，
//                 * requestPermissions在被拒绝一次后调用无效
//                 * 所以需要在else中自定义申请权限的弹窗引导用户自主授权
//                 *
//                 * */
//                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
//                        Manifest.permission.ACCESS_FINE_LOCATION)) {
//                    T.show("定位权限曾被拒绝，需要定位请打开");
//                    // Show an expanation to the user *asynchronously* -- don't block
//                    // this thread waiting for the user's response! After the user
//                    // sees the explanation, try again to request the permission.
//                } else {
//
//                    // No explanation needed, we can request the permission.   , Manifest.permission.ACCESS_FINE_LOCATION
//                    requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_RESULT);
//                    dialog = new CustomDialog(ChooseBuildingActivity.this, R.style.dialog_style,
//                            R.layout.dialog_custom, "请允许获取位置信息", "点击确定进入权限管理打开定位功能，是否手动授权?", false, false, new View.OnClickListener() {
//                        @Override
//                        public void onClick(View view) {
//                            Uri uri = Uri.parse("package:" + getPackageName());//包名
//                            Intent intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS", uri);
//                            startActivity(intent);
//                        }
//                    });
//                    dialog.show();
//
//
//                    // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
//                    // app-defined int constant. The callback method gets the
//                    // result of the request.
//                }
//            } else {
//                //获得BaiduMap对象
//                mBaiduMap = mMvChooseBuilding.getMap();
//
//                mBuildingAdapter = new ChooseBuildingAdapter(context);
//                // 开启定位图层
//                mBaiduMap.setMyLocationEnabled(true);
//                mLocClient = new LocationClient(this);
//                mLocClient.registerLocationListener(myListener);
//
//                LocationClientOption option = new LocationClientOption();
//                initLocationConfiguration(option);
//
//                mLocClient.setLocOption(option);
//                mLocClient.start();
//            }
//
//
//        } else {
//            //获得BaiduMap对象
//            mBaiduMap = mMvChooseBuilding.getMap();
//
//            mBuildingAdapter = new ChooseBuildingAdapter(context);
//            // 开启定位图层
//            mBaiduMap.setMyLocationEnabled(true);
//            mLocClient = new LocationClient(this);
//            mLocClient.registerLocationListener(myListener);
//
//            LocationClientOption option = new LocationClientOption();
//            initLocationConfiguration(option);
//
//            mLocClient.setLocOption(option);
//            mLocClient.start();
//        }
//        mBuildingAdapter = new ChooseBuildingAdapter(context);
//
//        //搜索
//        mTvChooseBuildingSearch.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (mEtChooseBuildingSearch.getText().length() > 0) {
//                    presenter.searchBuilding(mEtChooseBuildingSearch.getText().toString(), false);
//
//                }
//            }
//        });
//
//    }
//
//
//    //初始化定位
//    private void initLocationConfiguration(LocationClientOption option) {
//        /**
//         * 高精度定位模式：这种定位模式下，会同时使用网络定位和GPS定位，优先返回最高精度的定位结果；
//         *低功耗定位模式：这种定位模式下，不会使用GPS进行定位，只会使用网络定位（WiFi定位和基站定位）；
//         *仅用设备定位模式：这种定位模式下，不需要连接网络，只使用GPS进行定位，这种模式下不支持室内环境的定位。
//         */
//        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
//        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
//        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
//        option.setOpenGps(true);//可选，默认false,设置是否使用gps
//        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
//        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
//        option.setIgnoreKillProcess(true);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
//        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
//        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
//        option.setScanSpan(1000000);
//    }
//
//
//    @RequiresApi(api = Build.VERSION_CODES.M)
//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        if (requestCode == LOCATION_RESULT) {
//            if (grantResults.length > 0) {
//                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {//授权成功
//                    T.show("授权成功");
//                } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {//点击拒绝授权
//
//                    if (ActivityCompat.shouldShowRequestPermissionRationale(this
//                            , Manifest.permission.ACCESS_COARSE_LOCATION)) {//点击拒绝，再次弹出
//
//                        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
//
//                    } else { // 选择不再询问，并点击拒绝，弹出提示框
//                        dialog = new CustomDialog(ChooseBuildingActivity.this, R.style.dialog_style,
//                                R.layout.dialog_custom, "缺少权限2", "定位权限曾被拒绝，手动授权?", false, false, new View.OnClickListener() {
//                            @Override
//                            public void onClick(View view) {
//                                Uri uri = Uri.parse("package:" + getPackageName());//包名
//                                Intent intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS", uri);
//                                startActivity(intent);
//                            }
//                        });
//                        dialog.show();
//                    }
//                }
//            }
//        }
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//    }
//
//    /**
//     * 定位SDK监听函数
//     */
//    public class MyLocationListenner implements BDLocationListener {
//
//        @Override
//        public void onReceiveLocation(BDLocation location) {
//
//            // map view 销毁后不在处理新接收的位置
//            if (location == null || mMvChooseBuilding == null) {
//                return;
//            }
//            MyLocationData locData = new MyLocationData.Builder()
//                    .accuracy(location.getRadius())
//                    // 此处设置开发者获取到的方向信息，顺时针0-360
//                    .direction(100).latitude(location.getLatitude())
//                    .longitude(location.getLongitude()).build();
//
//            mBaiduMap.setMyLocationData(locData);
//            if (isFirstLoc) {
//                isFirstLoc = false;
//                LatLng ll = new LatLng(location.getLatitude(),
//                        location.getLongitude());
//                MapStatus.Builder builder = new MapStatus.Builder();
//                builder.target(ll).zoom(18.0f);
//                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
//            }
//
//            List<Poi> list = location.getPoiList();// POI数据
//            if (list != null) {
//                List<BuildingData> listBuildingData = new ArrayList<>();
//                BuildingData buildingData = new BuildingData();
//                buildingData.setBuilderName(list.get(0).getName());
//                buildingData.setAddress(location.getAddrStr());
//                //第一次定位后的地址如果不是已开通的地址，点击后联系客服在Aadapter中处理
//                //是已开通的地址，点击后联系客服在view.dialToServer中处理
//                presenter.searchBuilding(buildingData.getBuilderName(), true);       //第二个参数是标识是否是定位后调用的搜索
//                listBuildingData.add(buildingData);
//                mBuildingAdapter.clearAll();
//                mBuildingAdapter.addALL(listBuildingData);
//                mLvChooseBuilding.setAdapter(mBuildingAdapter);
//            }
//
//            Button bubble = new Button(getApplicationContext());
//            bubble.setText("我的位置");
//            if (infoWindow == null) {
//                infoWindow = new InfoWindow(bubble, new LatLng(location.getLatitude(), location.getLongitude()), -47);
//                mBaiduMap.showInfoWindow(infoWindow);
//            }
//        }
//
//
//    }
//
//
//    @Override
//    public void showBuilding(Building building) {
//        depth++;
//        mBuildingAdapter = new ChooseBuildingAdapter(context, building.getData());
//        mBuildingAdapter.setOpened(true);
//        mLvChooseBuilding.setAdapter(mBuildingAdapter);
//    }
//
//    @Override
//    public void dialToServer() {
//        dialog = new CustomDialog(context, R.style.dialog_style,
//                R.layout.dialog_custom, "搜索的大楼未开通配送服务", "是否咨询客服?", false, false, new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                dialog.dismiss();
//                Intent intent = new Intent();
//                Uri uri = Uri.parse("tel:" + Constant.SERVICE_TEL);
//                intent = new Intent(Intent.ACTION_DIAL, uri);
//                context.startActivity(intent);
//            }
//        });
//        dialog.show();
//    }
//
//    @Override
//    public void showRoad(Road road) {
//        depth++;
//        mRoadAdapter = new ChooseRoadAdapter(context, road.getData());
//        mLvChooseBuilding.setAdapter(mRoadAdapter);
//    }
//
//    @Override
//    public void setAdapterStatus() {
//        if (mBuildingAdapter != null) {
//            mBuildingAdapter.setOpened(false);
//        }
//
//    }
//
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onEventRoad(RoadData data) {
//        presenter.getBuilding(data.getId());
//    }
//
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onEventFinish(FinishEvent event) {
//        if (event.getActivityName().equals(getClass().getSimpleName())) {
//            this.finish();
//        }
//    }
//
//    @Override
//    protected void destroyView() {
//        EventBus.getDefault().unregister(this);
//
//        if (mBuildingAdapter != null) {
//            mBuildingAdapter.clearAll();
//        }
//        // 退出时销毁定位
//        if (mLocClient != null) {
//            mLocClient.stop();
//        }
//        // 关闭定位图层
//        if (mBaiduMap != null) {
//            mBaiduMap.setMyLocationEnabled(false);
//        }
//        if (mMvChooseBuilding != null) {
//            mMvChooseBuilding.onDestroy();
//            mMvChooseBuilding = null;
//        }
//        super.destroyView();
//    }
//
////    @Override
////    public void onBackPressed() {
////        if(depth <= 1){
////            depth = 0;
////            super.onBackPressed();
////        }else if(depth == 2){
////            depth--;
//////            mLvChooseBuilding.setAdapter(mRoadAdapter);
////        }
////    }
//
//    @Override
//    protected void onPause() {
//        mMvChooseBuilding.onPause();
//        super.onPause();
//    }
//
//    @Override
//    protected void onResume() {
//        mMvChooseBuilding.onResume();
//        super.onResume();
//    }
//
//}

package com.breakfast.fun.ui.user.address;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.breakfast.fun.R;
import com.breakfast.fun.adapter.user.ChooseBuildingAdapter;
import com.breakfast.fun.adapter.user.ChooseRoadAdapter;
import com.breakfast.fun.base.BaseActivity;
import com.breakfast.fun.data.entity.user.address.Building;
import com.breakfast.fun.data.entity.user.address.Road;
import com.breakfast.fun.data.entity.user.address.RoadData;
import com.breakfast.fun.event.FinishEvent;
import com.breakfast.fun.util.L;
import com.breakfast.fun.util.T;
import com.breakfast.fun.view.widget.TitleBarView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.Bind;

public class ChooseBuildingActivity extends BaseActivity<ChooseBuildingPresenter, ChooseBuildingModel> implements ChooseBuildingContract.View {

    @Bind(R.id.tbv_choose_building)
    TitleBarView mTbvChooseBuilding;
    @Bind(R.id.et_choose_building_search)
    EditText mEtChooseBuildingSearch;
    @Bind(R.id.tv_choose_building_search)
    TextView mTvChooseBuildingSearch;
    @Bind(R.id.lv_choose_building)
    ListView mLvChooseBuilding;

    private ChooseRoadAdapter mRoadAdapter;
    private ChooseBuildingAdapter mBuildingAdapter;

    private Road curRoad = null;

    private static int depth = 0;

    @Override
    public int getLayoutId() {
        return R.layout.activity_choose_building;
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);

        mTbvChooseBuilding.setTitleNoRight("选择大楼");
        mTbvChooseBuilding.setBack(this);

        mTvChooseBuildingSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mEtChooseBuildingSearch.getText().length() > 0) {
                    presenter.searchBuilding(mEtChooseBuildingSearch.getText().toString());
                }
            }
        });

        mEtChooseBuildingSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s)) {
                    if (mRoadAdapter != null) {
                        depth = 1;
                        mLvChooseBuilding.setAdapter(mRoadAdapter);
                    }
                }
            }
        });

    }

    @Override
    public void showBuilding(Building building) {
        if (null == building) {
            mLvChooseBuilding.setAdapter(null);
        } else {
            depth++;
            mBuildingAdapter = new ChooseBuildingAdapter(context, building.getData());
            mLvChooseBuilding.setAdapter(mBuildingAdapter);
        }
    }

    @Override
    public void showRoad(Road road) {
        depth++;
        curRoad = road;
        mRoadAdapter = new ChooseRoadAdapter(context, road.getData());
        mLvChooseBuilding.setAdapter(mRoadAdapter);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventRoad(RoadData data) {
        presenter.getBuilding(data.getId());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventFinish(FinishEvent event) {
        if (event.getActivityName().equals(getClass().getSimpleName())) {
            this.finish();
        }
    }

    @Override
    protected void destroyView() {
        super.destroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onBackPressed() {
        if (depth <= 1) {
            depth = 0;
            super.onBackPressed();
        } else if (depth == 2) {
            depth--;
            mLvChooseBuilding.setAdapter(mRoadAdapter);
        }
    }
}

